package net.iiyasvn;

import java.util.HashMap;
import java.util.Map;

import net.iiyasvn.adapter.TopicAdapter;
import net.iiyasvn.common.Constants;
import net.iiyasvn.model.TopicInfo;
import net.iiyasvn.model.TopicInfoList;
import net.iiyasvn.utils.IIYaClient;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.Gson;

public class TopicActivity extends ListActivity {
	private TopicAdapter topicAdapter;
	private LinearLayout loadingLayout;
	private TopicInfoList topicInfoList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.topic_list);
		initData();
	}
	public void initData(){
		loadingLayout = (LinearLayout)findViewById(R.id.loadingprogress);
		loadingLayout.setVisibility(View.VISIBLE);
		MediaPlayer mediaPlayer;
        mediaPlayer = MediaPlayer.create(this, R.raw.newblogtoast);
        mediaPlayer.start();
		new Thread(r).start();
	}
	Handler myHandler = new Handler(){
		public void handleMessage(Message msg){
			String result = (String)msg.obj;
			try{
				Gson gson = new Gson();
				topicInfoList = gson.fromJson(result, TopicInfoList.class);
			}catch (Exception e) {
				e.printStackTrace();
			}
			topicAdapter = new TopicAdapter(topicInfoList, TopicActivity.this);
			ListView listView = getListView();
			listView.setAdapter(topicAdapter);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					TopicInfo topicInfo = topicInfoList.getInfo().get(arg2);
					System.out.println(topicInfo);
//					Intent intent = new Intent();
//					intent.putExtra("id", topicInfo.getId());
//					intent.setClass(TopicActivity.this, UserInfoActivity.class);
//					startActivity(intent);
				}
			});
			loadingLayout.setVisibility(View.GONE);
			super.handleMessage(msg);
		}
	};
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			String result = null;
			try {
				Map<String,String> keyValues = new HashMap<String,String>();
				keyValues.put("format", "json");
				IIYaClient iiYaClient = new IIYaClient();
				result = iiYaClient.doGet(Constants.GETTOPIC, keyValues);
				System.out.println("result--------->" + result);
	        } catch (Exception e) {
	        	e.printStackTrace(); 
	        }
	        Message msg = myHandler.obtainMessage();
			msg.obj= result;
	        myHandler.sendMessage(msg);
			
		}
	};
	
}
